<template>
  <div class="tablePageWarp">
    <div class="commonSelectWidth table-page-search-wrapper" style="margin-bottom:5px">
      <a-form layout="vertical" >
        <a-row :gutter="[16,0]">
          <!-- VIN -->
          <!-- <a-col :span="5">
            <a-form-model-item :label="$t('VIN')">
              <a-input v-model="queryParam.vin" :placeholder="$t('pleaseInput') + 'VIN'" @keyup.enter="refreshData(true)" allow-clear :maxLength="17"/>
            </a-form-model-item>
          </a-col> -->
          <!-- 车型 -->
          <a-col :span="6">
            <a-form-model-item :label="$t('vehicleModel')">
              <car-model-select
                :query="{ }"
                :default-value="queryParam.modelId"
                :hasAll="false"
                :clear="true"
                mode="default"
                @changeoption="(val) => {queryParam.modelId = val;refreshData(true);}"
                style="width: 100%"
              ></car-model-select>
            </a-form-model-item>
          </a-col>
          <!-- 任务名称 -->
          <a-col :span="6">
            <a-form-model-item :label="$t('campaignName')">
              <a-input v-model="queryParam.name" :placeholder="$t('pleaseInput') + $t('campaignName')" @keyup.enter="refreshData(true)" allow-clear/>
            </a-form-model-item>
          </a-col>
          <!-- 任务状态 -->
          <a-col :span="6">
            <a-form-model-item :label="$t('campaignStatus')">
              <a-select
                v-model="queryParam.status"
                showSearch
                allow-clear
                optionFilterProp="children"
                @change="refreshData(true)"
                :filterOption="$commonFun.filterOption"
                :placeholder="$t('pleaseSelect')+ $t('campaignStatus')"
                :maxTagCount="1"
                style="width:100%"
              >
                <a-select-option
                  key="NOT_STARTED"
                  value="NOT_STARTED"
                  title="待生效"
                >待生效
                </a-select-option>
                <a-select-option
                  key="EXECUTING"
                  value="EXECUTING"
                  title="已生效"
                >已生效
                </a-select-option>
                <a-select-option
                  key="SUCCESS"
                  value="SUCCESS"
                  title="成功"
                >成功
                </a-select-option>
                <a-select-option
                  key="FAILED"
                  value="FAILED"
                  title="失败"
                >失败
                </a-select-option>
                <a-select-option
                  key="CANCELED"
                  value="CANCELED"
                  title="已取消"
                >已取消
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <!-- 创建人 -->
          <a-col :span="6">
            <a-form-model-item label="创建人">
              <a-select
                v-model="queryParam.createBy"
                showSearch
                allow-clear
                optionFilterProp="children"
                @change="refreshData(true)"
                :filterOption="$commonFun.filterOption"
                :placeholder="$t('pleaseSelect')+ '创建人'"
                :maxTagCount="1"
                style="width:100%"
              >
                <a-select-option
                  v-for="(item,index) in userList"
                  :key="'user'+index"
                  :value="item.id"
                  :title="item.name"
                >
                  {{ item.name + '('+item.account+')' }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <!-- 升级类型 -->
          <a-col :span="6">
            <a-form-model-item :label="$t('upgradeType')">
              <a-select
                v-model="queryParam.type"
                showSearch
                allow-clear
                optionFilterProp="children"
                @change="refreshData(true)"
                :filterOption="$commonFun.filterOption"
                :placeholder="$t('pleaseSelect')+ $t('upgradeType')"
                :maxTagCount="1"
                style="width:100%"
              >
                <a-select-option
                  v-for="item in upgradeTriggerType"
                  :key="item.value"
                  :value="item.value"
                  :title="item.name"
                >{{ item.name }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <!-- 是否静默升级 -->
          <a-col :span="6" v-if="queryParam.type=='AUTO'">
            <a-form-model-item :label="$t('是否静默升级')">
              <a-select
                v-model="queryParam.silenceUpgrade"
                showSearch
                allow-clear
                optionFilterProp="children"
                @change="refreshData(true)"
                :filterOption="$commonFun.filterOption"
                :placeholder="$t('pleaseSelect')+ $t('是否静默升级')"
                :maxTagCount="1"
                style="width:100%"
              >
                <a-select-option
                  key="1"
                  :value="true"
                  title="静默升级">静默升级</a-select-option>
                <a-select-option
                  key="0"
                  :value="false"
                  title="非静默升级">非静默升级</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <!-- 是否强制升级 -->
          <a-col :span="6" v-if="queryParam.type=='USER'">
            <a-form-model-item :label="$t('是否强制升级')">
              <a-select
                v-model="queryParam.forceUpgrade"
                showSearch
                allow-clear
                optionFilterProp="children"
                @change="refreshData(true)"
                :filterOption="$commonFun.filterOption"
                :placeholder="$t('pleaseSelect')+ $t('是否强制升级')"
                :maxTagCount="1"
                style="width:100%"
              >
                <a-select-option
                  key="1"
                  :value="true"
                  title="静默升级">强制升级</a-select-option>
                <a-select-option
                  key="0"
                  :value="false"
                  title="非静默升级">非强制升级</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" style="margin-top: 23px;">
            <div class="searchBtns">
              <a-button-group>
                <auth-button
                  type="primary"
                  :auth="loopTestTaskPerms.view"
                  @click="refreshData(true)">
                  <i class="iconfont icon-chazhao"></i>
                  {{ $t('inquiry') }}
                </auth-button>
                <a-button @click="initiSelectValue">
                  <i class="iconfont icon-qingkong"></i>
                  {{ $t('clear') }}
                </a-button>
              </a-button-group>
              <auth-button
                :auth="loopTestTaskPerms.add"
                @click="newTask">
                <i class="iconfont icon-xinjian"></i>{{ $t('new') }}
              </auth-button>
            </div>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <s-table
      class="h100 withMinHeightTbodyBox"
      ref="table"
      :columns="columns"
      :data="loadData"
      :scrollX="1900"
      :rowKey="(record, index) => index"
      size="default" >
      <template slot-scope="text" v-for="column in commonColumns" :slot="column.scopedSlots.customRender">
        <table-ellipsis :text="text || '-'" :key="column.key"></table-ellipsis>
      </template>
      <template slot="status" slot-scope="text, record">
        <table-ellipsis :text="$store.getters.getDictCodeObj('loopTestTaskStatusDictCode')[text] || '-'"></table-ellipsis>
      </template>
      <template slot="modelName" slot-scope="text, record">
        <table-ellipsis :text="record.model?record.model.name: '-' || '-'"></table-ellipsis>
      </template>
      <template slot="modelCode" slot-scope="text, record">
        <table-ellipsis :text="record.model?record.model.code: '-' || '-'"></table-ellipsis>
      </template>
      <template slot="company" slot-scope="text, record">
        <table-ellipsis :text="record.model?$store.getters.getDictCodeObj('companyDictCode')[record.model.company]: '-' || '-'"></table-ellipsis>
      </template>
      <template slot="operation" slot-scope="text, record">
        <span style="display: flex;">
          <auth-button
            :auth="loopTestTaskPerms.view"
            @click="openDetail(record)"
            class="set-margin"
            type="primary"
            :ghost="true"
            size="small">
            <i class="iconfont icon-yanjing"/>{{ $t('详情') }}</auth-button>
          <auth-button @click="newTask(record)" class="set-margin" type="primary" :ghost="true" size="small"><i class="iconfont icon-fuzhi"/>{{ $t('copy') }}</auth-button>
          <!-- 隐藏操作列取消任务按钮 -->
          <!-- <auth-button
            :auth="loopTestTaskPerms.cancel"
            :disabled="record.status==='SUCCESS'||record.status==='FAILED' ||record.status==='CANCELED'"
            @click="handelCancel(record)"
            style="word-break: keep-all;"
            type="danger"
            :ghost="true"
            size="small">
            <a-icon type="close" />{{ $t('cancel') }}</auth-button> -->
        </span>
      </template>
    </s-table>
  </div>
</template>
<script>
import TableEllipsis from '@/components/Ellipsis/TableEllipsis'
import { STable } from '@/components'
import AuthText from '@/components/AuthText'
import moment from 'moment'
import AuthButton from '@/components/AuthButton'
import { LoopTestTaskListColumns } from './test/list'
import CarModelCodeSelect from '@/views/components/CarModelCodeSelect'
import { mapState } from 'vuex'
import CarModelSelect from '@/views/components/CarModelSelect'
import NewLoopTestTask from '@/views/task/components/NewLoopTestTask.vue'
import { minxinDrawerUse } from '@/utils/mixin'
import LoopTestTaskDetail from '@/views/task/components/LoopTestTaskDetail.vue'
import { loopTestTaskPerms } from '@/config/permission/index'
const initQueryParam = {
  // vin: undefined,
  modelId: undefined,
  createBy: undefined,
  // 任务名称
  name: undefined,
  // 任务状态
  status: undefined,
  // 升级类型
  type: undefined,
  // 静默
  silenceUpgrade: undefined,
  // 强制
  forceUpgrade: undefined
}
export default {
  mixins: [minxinDrawerUse],
  components: {
    TableEllipsis,
    STable,
    AuthText,
    AuthButton,
    CarModelCodeSelect,
    CarModelSelect,
    NewLoopTestTask,
    LoopTestTaskDetail
  },
  props: {
  },
  computed: {
    commonColumns () {
      return this.columns.filter(item => !item.special)
    },
    ...mapState({
      instantUpdateTime: (state) => state.app.instantUpdateTime,
      upgradeTriggerType: (state) => state.dict.upgradeTriggerTypeDictCode
    })
  },
  created () {
    this.$store.dispatch('getLoopTestTaskStatusDictCodeData')
    this.$store.dispatch('getTaskUpdateDictCodeData')
    this.$store.dispatch('getUpgradeTriggerTypeDictCodeData')
    this.$store.dispatch('getCompanyDictCodeData')
    if (this.$route.path === '/develop-test/loopTestTask') {
      this.testType = 'develop'
    } else if (this.$route.path === '/channel-test/loopTestTask') {
      this.testType = 'channel'
    } else if (this.$route.path === '/uat-test/loopTestTask') {
      this.testType = 'uat'
    }
  },
  mounted () {
    this.getUsers()
  },
  data () {
    return {
      loopTestTaskPerms,
      moment,
      columns: [...LoopTestTaskListColumns],
      // 列表数据
      tableData: [],
      queryParam: { ...initQueryParam },
      // 创建人数据
      userList: [],
      // 测试类型
      testType: ''
    }
  },
  methods: {
    // 取消任务
    handelCancel (record) {
      const vm = this
      this.$confirm({
        title: vm.$t('cancelTask'),
        content: vm.$t('newCancelTaskTip').replace('__TaskName__', record.name),
        class: 'confirmStyle',
        width: 378,
        onOk () {
          vm.$api.cancelLoopTestTask(record.id).then(() => {
            vm.$message.success(vm.$t('successfullyOperation'))
            vm.refreshData(true)
          })
        },
        onCancel () { }
      })
    },
    // 详情
    openDetail (record) {
      const vars = {
        taskId: record.id,
        taskName: record.name,
        status: record.status,
        LoopRefreshData: this.refreshData
      }
      this.showRightDrawer(LoopTestTaskDetail, (record.name + '详情'), [], '88%', vars)
    },
    // 新建
    newTask (record) {
      const vm = this
      const buttons = this.getRightDrawerFooterButtons({
        method: 'saveData',
        callback () {
          vm.refreshData(true)
        }
      })
      const vars = {
        testType: this.testType,
        taskInfo: record?record:{} 
      }
      if (record) {
        vm.showRightDrawer(NewLoopTestTask,this.$t('copy'), buttons, '88%', vars);
      } else {
        vm.showRightDrawerNoReset(NewLoopTestTask,this.$t('new'), buttons, '88%', vars);
      }
    },
    // 新建循环测试任务
    saveData (data) {
      return new Promise((resolve, reject) => {
        this.$api.addLoopTestTask(data).then(res=>{
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 获取创建人
    getUsers () {
      this.$api.getUserPageData({ pageSize: 5000 }).then(res => {
        this.userList = res.data
      }).catch((res) => this.$message.error('获取创建人信息失败！'))
    },
    // 下拉框 重置和初始化
    initiSelectValue () {
      this.queryParam = { ...initQueryParam }
      this.refreshData(true)
    },
    // 刷新
    refreshData (isToFirstPage = false) {
      const vm = this
      vm.$nextTick(() => {
        this.$refs.table.refresh(isToFirstPage)
      })
    },
    loadData (parameter) {
      const vm = this
      // 如果是全部则不传值给后端
      const JnqueryParam = JSON.parse(JSON.stringify(vm.queryParam))
      // eslint-disable-next-line no-restricted-syntax
      for (const key in JnqueryParam) {
        if (JnqueryParam[key] === '') {
          JnqueryParam[key] = undefined
        }
      }
      this.tableData = []
      const apiPromise = vm.$api.getLoopTestTaskList({ ...parameter, ...JnqueryParam })
      // const apiPromise = vm.$api.getTestTaskPageData({ ...parameter, ...JnqueryParam },'develop')
      return new Promise((resolve, reject) => {
        return apiPromise.then(res => {
          if (res.data) {
            this.tableData = res.data
          }
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
  }
}
</script>
<style scoped lang="less">
 ::v-deep .ant-form-item-label {
  padding-bottom: 2px;
}
::v-deep .ant-form-item {
  margin-bottom: 0;
}
.set-margin {
  margin-right: 12px;
}
</style>
